<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
// import { useAuth } from '../composables/useAuth'
// import { supabase } from '../config/supabase'
import { ElMessage } from 'element-plus'
import { useAuthStore } from '../stores/authStore'

const router = useRouter()
// const { signIn, loading, error } = useAuth()
const authStore = useAuthStore()

const form = ref({
  username: '',
  password: ''
})

const resendLoading = ref(false)

const handleLogin = async () => {
  if (!form.value.username || !form.value.password) {
    ElMessage.warning('请输入用户名和密码')
    return
  }
  
  const success = await authStore.login(form.value.username, form.value.password)
  if (success) {
    router.push('/')
  }
}

const handleGoRegister = () => {
  router.push('/register')
}

const handleResendEmail = async () => {
  try {
    resendLoading.value = true
    // 这里可以调用真实的重发邮件API
    // 模拟重发成功
    await new Promise(resolve => setTimeout(resolve, 1000))
    ElMessage.success('验证邮件已重新发送，请查收')
  } catch (err) {
    ElMessage.error(err.message || '发送失败')
  } finally {
    resendLoading.value = false
  }
}
</script>

<template>
  <div class="login-container">
    <el-card class="login-card">
      <template #header>
        <div class="header">
          <h2>登录</h2>
          <el-link type="primary" @click="handleGoRegister">没有账号？去注册</el-link>
        </div>
      </template>
      <el-form :model="form">
        <el-form-item>
          <el-input v-model="form.username" placeholder="用户名" />
        </el-form-item>
        <el-form-item>
          <el-input v-model="form.password" type="password" placeholder="密码" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :loading="authStore.loading" @click="handleLogin" block>
            登录
          </el-button>
        </el-form-item>
      </el-form>
      <el-alert
        v-if="authStore.error?.includes('Email not confirmed')"
        type="warning"
        show-icon
      >
        <template #title>
          邮箱未验证，请先验证邮箱
          <el-button 
            type="primary" 
            link 
            :loading="resendLoading"
            @click="handleResendEmail"
          >
            重新发送验证邮件
          </el-button>
        </template>
      </el-alert>
      <el-alert
        v-else-if="authStore.error"
        type="error"
        :title="authStore.error"
        show-icon
      />
    </el-card>
  </div>
</template>

<style scoped>
.login-container {
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: var(--el-bg-color-page);
}

.login-card {
  width: 400px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.el-alert :deep(.el-alert__title) {
  display: flex;
  align-items: center;
  gap: 8px;
}
</style>
